package com.jh.fcsm.service.sys.impl;

import java.util.*;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.jh.fcsm.beans.sys.vo.DataFiled;
import com.jh.fcsm.service.sys.SysTableConfigService;
import com.jh.fcsm.util.AppUserUtil;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jh.fcsm.beans.sys.SysTableSet;
import com.jh.fcsm.beans.sys.vo.SysTableSetVo;
import com.jh.fcsm.common.exception.ServiceException;
import com.jh.fcsm.common.BaseServiceImpl;
import com.jh.fcsm.util.security.UUIDUtils;
import com.jh.fcsm.dao.sys.SysTableSetMapper;
import com.jh.fcsm.service.sys.SysTableSetService;
import com.jh.fcsm.constant.CommonConstant;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 *  用户格设置Service业务层处理
 * 
 * @author linq
 * @date 2024-01-31
 */
@Service
@Transactional(readOnly = true)
public class SysTableSetServiceImpl extends BaseServiceImpl<SysTableSetMapper, SysTableSet> implements SysTableSetService{
	
	private static final Logger logger = LoggerFactory.getLogger(SysTableSetServiceImpl.class);
    @Autowired
    private SysTableSetMapper sysTableSetMapper;
	@Autowired
	private SysTableConfigService sysTableConfigService;


	/**
	 * 保存或更新列表显示字段
	 * @param sysTableSetVo
	 * @return
	 */
	@Override
	@Transactional(readOnly = false)
	public String saveListTableset(SysTableSetVo sysTableSetVo) {
		if (sysTableSetVo == null) {
			throw new ServiceException("数据异常");
		}
//		if (CollectionUtils.isEmpty(sysTableSetVo.getSysTableSetListVo())) {
//			throw new ServiceException("数据异常");
//		}
		sysTableSetVo.setUserId(AppUserUtil.getCurrentUserId());
		sysTableSetVo.setCreateTime(new Date());
//		JSONArray jsonArray = new JSONArray(sysTableSetVo.getSysTableSetListVo());
//		sysTableSetVo.setListField(jsonArray.toJSONString());


		SysTableSet record = findByKeyAndUserIdForInner(sysTableSetVo.getTableFlag(), AppUserUtil.getCurrentUserId());

		if (record == null || !StringUtils.hasText(record.getId())) {
			//新增
			sysTableSetVo.setId(UUIDUtils.getUUID());
			sysTableSetMapper.insertSelective(sysTableSetVo);
		} else {
			//避免页面传入修改
			sysTableSetVo.setId(record.getId());
			sysTableSetVo.setYn(null);
			sysTableSetMapper.updateByPrimaryKeySelective(sysTableSetVo);
		}
		return sysTableSetVo.getId();
	}
	/**
	 * 获取用户自定义列表
	 *
	 * @param key
	 * @param userId
	 * @return
	 */
	@Override
	public SysTableSet findByKeyAndUserId(String key, String userId) {
		Example example = new Example(SysTableSet.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("yn", CommonConstant.FLAG_YES);
		criteria.andEqualTo("tableFlag", key)
				.andEqualTo("userId", userId);
		example.orderBy("createTime").desc();
		List<SysTableSet> sysTableSetList = sysTableSetMapper.selectByExample(example);

		// 读取默认的配置
		JSONArray listHabit = sysTableConfigService.findListJsonByFlag(key);
		SysTableSet sysTableSet=new SysTableSetVo();

		if (CollectionUtils.isEmpty(sysTableSetList)) {
			// 用户未设置过
			sysTableSet.setTableFlag(key);
			sysTableSet.setListField(listHabit.toJSONString());
			return sysTableSet;
		} else {
			// 根据默认配置，多删少补用户习惯字段
			sysTableSet = sysTableSetList.get(0);
			if (StringUtils.isEmpty(sysTableSet.getListField())) {
				sysTableSet.setListField(listHabit.toJSONString());
				return sysTableSet;
			}
			sysTableSet.setListField( compareJSONArray(listHabit, JSONArray.parseArray( sysTableSet.getListField())).toJSONString());

		}

		return sysTableSet;
	}

	/**
	 * 获取用户自定义导出属性
	 * @param key
	 * @param userId
	 * @return
	 */
	@Override
	public SysTableSet findByCurrentUserForExport(String key, String userId) {
		Example example = new Example(SysTableSet.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("yn", CommonConstant.FLAG_YES);
		criteria.andEqualTo("tableFlag", key)
				.andEqualTo("userId", userId);
		example.orderBy("createTime").desc();
		List<SysTableSet> sysTableSetList = sysTableSetMapper.selectByExample(example);

		if (CollectionUtils.isEmpty(sysTableSetList)) {
			return null;
		}
		SysTableSet habit = sysTableSetList.get(0);
		JSONArray excelJsonByFlag = sysTableConfigService.findExcelJsonByFlag(key);
		habit.setListField(excelJsonByFlag.toJSONString());
		return habit;
	}

	@Override
	public SysTableSet findByKeyAndUserIdForInner(String key, String userId) {
		Example example = new Example(SysTableSet.class);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("yn", CommonConstant.FLAG_YES);
		criteria.andEqualTo("tableFlag", key)
				.andEqualTo("userId", userId);
		example.orderBy("createTime").desc();
		List<SysTableSet> sysTableSetList = sysTableSetMapper.selectByExample(example);
		return CollectionUtils.isEmpty(sysTableSetList) ? null : sysTableSetList.get(0);
	}

	/**
	 * 比较默认字段与用户字段，主要解决默认字段调整，用户字段不更新的问题
	 * @param defaultJson 默认字段
	 * @param habitJson 用户字段
	 * @return
	 */
	private JSONArray compareJSONArray(JSONArray defaultJson, JSONArray habitJson) {

		JSONArray array = new JSONArray();
		defaultJson.stream().forEach(de -> {
			JSONObject obj = new JSONObject();

			Optional<Object> first = habitJson.stream().filter(hab -> {
				JSONObject habObj = (JSONObject) hab;
				JSONObject deObj = (JSONObject) de;
				return Objects.equals(habObj.get("fieldName"), deObj.get("fieldName"));
			}).findFirst();
			if (first.isPresent()) {
				obj = (JSONObject) first.get();
				// 部分属性按默认的来,以保证这部分属性作调整时，能全局更改
				JSONObject de1 = (JSONObject) de;
				obj.put("fieldType", de1.get("fieldType"));
				obj.put("whetherForceShow", de1.get("whetherForceShow"));
				obj.put("fieldCnName", de1.get("fieldCnName"));
				obj.put("align", de1.get("align"));
				// width如果为空，读取默认配置的
				obj.put("width", obj.get("width") == null ? de1.get("width") : obj.get("width"));

			} else {
				// 说明是新加的
				obj = (JSONObject) de;
			}
			array.add(obj);
		});

		return array;
	}


	@Override
	public List<DataFiled> getExportColumns(String key, String userId) {
		SysTableSet sysTableSet = findByKeyAndUserIdForInner(key, userId);

		List<DataFiled> dataFileds = new ArrayList<>();
		if (Objects.isNull(sysTableSet)) {
			// 默认导出全部
			JSONArray excelJsonByFlag = sysTableConfigService.findExcelJsonByFlag(key);
			for (Object field: excelJsonByFlag) {
				JSONObject deObj = (JSONObject) field;
				DataFiled data=new DataFiled();
				String fieldName = String.valueOf(deObj.get("tableFlag"));
				String fieldCnName = String.valueOf(deObj.get("name"));
				data.setKey(fieldName);
				data.setName(fieldCnName);
				dataFileds.add(data);
			};

		} else {
			//把json中的exportColumns反序列化 List<DataFiled>
			dataFileds = JSONArray.parseArray(JSONObject.parseObject(sysTableSet.getExpField()).get("exportColumns").toString(), DataFiled.class);
		}
		if (CollectionUtils.isEmpty(dataFileds)) {
			throw new ServiceException("excel导出字段转换错误");
		}
		return dataFileds;
	}
}
